//
//  HelperVC.swift
//  ShareUmbrella
//
//  Created by keng fu on 2017/8/17.
//  Copyright © 2017年 尧尚信息科技. All rights reserved.
//

import UIKit
import YSKit
import SWRevealViewController
import RxSwift
import TSMessages
import CoreLocation
import SwiftyJSON


class HelperVC:  MapViewVC {
    
    var arrForUsers = NSMutableArray()
    
    var viewForInput = UIView()
    var lblCurrentLocate = UILabel()
    var lblDestLocate = UITextField()
    var btnHelp = UIButton()
    var stopHelpButton = UIButton()
    var btnSelectStartAddr = UIButton()
    var btnSelectEndAddr = UIButton()
    
    var viewForContainer = UIView()
    var btnCall = UIButton()
    var btnLocate = UIButton()
    var imageHeader = UIImageView()
    var lblNickName = UILabel()
    var btnStart = UIButton()
    
    var endAddress: Variable<AddressModel?> = Variable(nil)
    var startAddress: Variable<AddressModel?> = Variable(nil)
    
    var lineView = UIView()
    
    var isStartAddress = false

    override func setup() {
        super.setup()
        self.showCustomNavigationBar = true
    }

    override func buildUI() {
        super.buildUI()
        self.title = I18n("VC.home.title")
        let revealController = self.revealViewController()!
        self.view.addGestureRecognizer(revealController.panGestureRecognizer())
        

        self.btnHelp.ys.customize { (view) in
            view.layer.cornerRadius = 20
            view.layer.masksToBounds = true
            view.ys.setImageAndTitle(imageName: "搜索", title: "开始求助", type: .left, space: 2.0)
            view.setTitleColor(.gray, for: .disabled)
            self.view.addSubview(view)
            view.backgroundColor = UIColor(colorLiteralRed: 65/255.0, green: 181/255.0, blue: 116/255.0, alpha: 1)
            view.snp.makeConstraints({ (make) in
                make.centerX.equalTo(self.view)
                make.bottom.equalTo(self.view.snp.bottom).offset(-50)
                make.width.equalTo(150)
                make.height.equalTo(40)
            })
        }
        self.stopHelpButton.ys.customize { (view) in
            view.layer.cornerRadius = 20
            view.layer.masksToBounds = true
            view.ys.setImageAndTitle(imageName: "搜索", title: "结束求助", type: .left, space: 2.0)
            view.setTitleColor(.gray, for: .disabled)
            self.view.addSubview(view)
            view.backgroundColor = .red
            view.isHidden = true
            view.snp.makeConstraints({ (make) in
                make.center.width.height.equalTo(self.btnHelp)

            })
        }

        
        self.viewForContainer.ys.customize { (view) in
            self.view.addSubview(view)
            view.backgroundColor = UIColor(colorLiteralRed: 0.9, green: 0.9, blue: 0.9, alpha: 0.7)
        
            view.snp.makeConstraints({ (make) in
                make.bottom.leading.trailing.equalTo(self.view)
                make.height.equalTo(220)
            })
        }

        self.imageHeader.ys.customize { (view) in
            self.viewForContainer.addSubview(view)
            view.image = UIImage(named: "头像7")
            view.layer.masksToBounds = true
            view.layer.cornerRadius = 75/2

            view.snp.makeConstraints({ (make) in
                make.top.equalTo(self.viewForContainer.snp.top).offset(30)
                make.centerX.equalTo(self.viewForContainer.snp.centerX)
                make.height.width.equalTo(75)
            })
        }
        
        self.lblNickName.ys.customize { (view) in
            view.text = "--"
            self.viewForContainer.addSubview(view)
            
            view.snp.makeConstraints({ (make) in
                make.top.equalTo(self.imageHeader.snp.bottom).offset(10)
                make.centerX.equalTo(self.viewForContainer.snp.centerX)
            })
        }
        
        self.btnCall.ys.customize { (button) in
            button.setImage(UIImage(named: "电话icon"), for: .normal)
            self.viewForContainer.addSubview(button)
            
            button.snp.makeConstraints({ (make) in
                make.trailing.equalTo(self.imageHeader.snp.leading).offset(-40)
                make.centerY.equalTo(self.imageHeader.snp.centerY)
                make.height.width.equalTo(40)
            })
        }
        
        self.btnLocate.ys.customize { (button) in
            button.setImage(UIImage(named: "定位icon"), for: .normal)
            self.viewForContainer.addSubview(button)
            
            button.snp.makeConstraints({ (make) in
                make.leading.equalTo(self.imageHeader.snp.trailing).offset(40)
                make.centerY.equalTo(self.imageHeader.snp.centerY)
                make.height.width.equalTo(40)
            })
        }
        
        self.btnStart.ys.customize { (view) in
            view.layer.cornerRadius = 20
            view.layer.masksToBounds = true
            view.setTitle("开始计时", for: .normal)
            self.viewForContainer.addSubview(view)
            view.backgroundColor = UIColor(colorLiteralRed: 65/255.0, green: 181/255.0, blue: 116/255.0, alpha: 1)
            
            view.snp.makeConstraints({ (make) in
                make.centerX.equalTo(self.viewForContainer)
                make.bottom.equalTo(self.viewForContainer.snp.bottom).offset(-30)
                make.width.equalTo(120)
                make.height.equalTo(40)
            })
        }
        

        
        self.viewForInput.ys.customize { (view) in
            self.view.addSubview(view)
            view.backgroundColor = UIColor.white
            view.layer.cornerRadius = 8
            view.layer.masksToBounds = true
            view.snp.makeConstraints({ (make) in
                make.bottom.equalTo(self.btnHelp.snp.top).offset(-30)
                make.height.equalTo(100)
                make.trailing.equalTo(self.view.snp.trailing).offset(-20)
                make.leading.equalTo(self.view.snp.leading).offset(20)
            })
        }
        
        self.btnSelectStartAddr.ys.customize { (view) in
            view.setTitleColor(UIColor.gray, for: .normal)
            view.setTitle("当前位置", for: .normal)
            self.viewForInput.addSubview(view)
            
            view.snp.makeConstraints({ (make) in
                make.top.leading.trailing.equalTo(self.viewForInput)
                make.height.equalTo(50)
            })
        }
        
        
        self.btnSelectEndAddr.ys.customize { (view) in
            view.setTitleColor(UIColor.gray, for: .normal)
            view.setTitle("请选择结束位置", for: .normal)
            self.viewForInput.addSubview(view)
            
            view.snp.makeConstraints({ (make) in
                make.bottom.leading.trailing.equalTo(self.viewForInput)
                make.height.equalTo(50)
            })
        }
        
        self.lineView = UIView(frame: .zero).ys.customize({ (lineview) in
            view.addSubview(lineview)
            lineview.backgroundColor = UIColor.lightGray
            lineview.snp.makeConstraints({ (make) in
                make.centerY.equalTo(self.viewForInput)
                make.leading.trailing.equalTo(self.viewForInput)
                make.height.equalTo(1)
            })
        })

        
        
        
        _ = self.btnStart.rx.tap
            .takeUntil(self.rx.deallocated)
            .subscribe(onNext: { [weak self](RxGestureTypeOptions) in
                guard let `self` = self else {
                    return
                }
                HUD.show()
                if self.btnStart.title(for: .normal) == "开始计时" {
                    _ = YSNetWorkManager.provider.requestJSON(YSStructTarget(AcceptAPI.startRouteAction(token: Auth.token, helpid: User.statusInfo.value!.info["helpid"].stringValue))).subscribe(onNext: { (data) in
                        self.btnStart.setTitle("结束计时", for: .normal)
                        self.btnStart.backgroundColor = .red

                        HUD.hide()
                    }, onError: {(ErrorType) in
                        HUD.hide()

                        TSMessage.showNotification(withTitle: "开始计时失败", type: .error)
                    })
                }else{
                    //获取帮助者的信息
                    var userInfo:JSON?

                    if let json =  User.statusInfo.value?.info {
                      userInfo = json["acceptHelpUser"]
                    }

                    _ = YSNetWorkManager.provider.requestJSON(YSStructTarget(AcceptAPI.stopRouteAction(token: Auth.token, helpid: User.statusInfo.value!.info["helpid"].stringValue))).subscribe(onNext: { (data) in
                        User.getStatus{
                            HUD.hide()
                        }
                        let vc = EndRouteVC()
                        vc.helpId = User.statusInfo.value!.info["helpid"].stringValue;
                        if let json =  User.statusInfo.value?.info {
                            vc.nickName = json["acceptHelpUser"]["name"].stringValue
                            vc.imageHeader = json["acceptHelpUser"]["avator"].stringValue
                        }
                        self.ys.push(vc, animated: true, withdata: userInfo)
                    }, onError: {(ErrorType) in
                        HUD.hide()

                        TSMessage.showNotification(withTitle: "结束计时失败", type: .error)
                    })

                }
                
                
            })
        _ = self.btnSelectEndAddr.rx.tap
            .takeUntil(self.rx.deallocated)
            .subscribe(onNext: { [weak self](RxGestureTypeOptions) in
                //选择结束位置
                let vc = SelectAddressVC()
                self?.isStartAddress = false
                self?.ys.push(vc)
            })
        
        _ = self.btnSelectStartAddr.rx.tap
            .takeUntil(self.rx.deallocated)
            .subscribe(onNext: { [weak self](RxGestureTypeOptions) in
                //选择开始位置
                let vc = SelectAddressVC()
                self?.isStartAddress = true
                self?.ys.push(vc)
                
            })
        
        
        
    }
    
    //
    override func buildRx() {
        super.buildRx()
        self.nearbyUserType = .acceptHelper
        
        _ = btnCall.rx.tap
            .takeUntil(self.rx.deallocated)
            .subscribe(onNext: { [weak self](RxGestureTypeOptions) in
                
                if let json =  User.statusInfo.value?.info {
                    let urlString = "tel://\(json["acceptHelpUser"]["phone"].stringValue)"
                    if let url = URL(string: urlString) {
                        //根据iOS系统版本，分别处理
                        if #available(iOS 10, *) {
                            UIApplication.shared.open(url, options: [:],
                                                      completionHandler: {
                                                        (success) in
                            })
                        } else {
                            UIApplication.shared.openURL(url)
                        }
                    }
                    
                }
                
                
            })

        _ = btnLocate.rx.tap
            .takeUntil(self.rx.deallocated)
            .subscribe(onNext: { [weak self](RxGestureTypeOptions) in
                guard let `self` = self, let location = Location.location.value else{
                    return
                }
                self.mapView.setCenter(location.coordinate, animated: true)
                
            })
        

        
        let everythingValid = Observable.combineLatest(
            self.startAddress.asObservable(),
            self.endAddress.asObservable()
        ) {(startAddress,endAddress) -> Bool in
            guard let  _ = startAddress, let _ = endAddress else{
                return false
            }
            return true
            }.shareReplay(1)
        
        //布局路线图
        _ = everythingValid.takeUntil(self.rx.deallocated).subscribe(onNext: { [weak self](_) in
            
            guard let  `self` = self else {
                return
            }
            self.startSearch()
        })
        
        
       _ = everythingValid.takeUntil(self.rx.deallocated)
            .bind(to: self.btnHelp.rx.isEnabled)

        _ = self.btnHelp.rx.tap
            .takeUntil(self.rx.deallocated)
            .subscribe(onNext: { [weak self](RxGestureTypeOptions) in
                //上报位置信息
                
                guard let  `self` = self else {
                    return
                }
                
                guard let e = self.endAddress.value, let s = self.startAddress.value else{
                    TSMessage.showNotification(withTitle: "请选择开始和结束位置", type: .warning)
                    return
                }
                HUD.show()

                _ = YSNetWorkManager.provider.requestJSON(YSStructTarget(AcceptAPI.askForHelpAction(token: Auth.token, from: ["latitude": s.latitude, "longitude": s.longitude, "startAddress": s.address], to:  ["latitude": e.latitude , "longitude": e.longitude , "endAddress": e.address ]))).subscribe(onNext: { (data) in
//                    
                    TSMessage.showNotification(withTitle: "请求成功, 正在等待服务器匹配", type: .success)
                    //更新状态
                    User.getStatus{
                        HUD.hide()
                    }

                }, onError: {(ErrorType) in
                    HUD.hide()

                    self.handle(withError: ErrorType)
                })
                
                
                
            })
        
        
        _ = self.stopHelpButton.rx.tap
            .takeUntil(self.rx.deallocated)
            .subscribe(onNext: { [weak self](RxGestureTypeOptions) in
                //上报位置信息
                
                guard let  `self` = self else {
                    return
                }
                HUD.show()
                _ = YSNetWorkManager.provider.requestJSON(YSStructTarget(AcceptAPI.stopAskForHelpAction(token: Auth.token, helpid: User.statusInfo.value?.info["helpid"].stringValue ?? ""))).subscribe(onNext: { (data) in
                    TSMessage.showNotification(withTitle: "结束帮助请求成功", type: .success)
                    //更新状态
                    User.getStatus{ [weak self] in
                        guard let  `self` = self else {
                            return
                        }
                        self.removeRoute()
                        HUD.hide()

                    }

                }, onError: {(ErrorType) in
                    HUD.hide()
                    self.handle(withError: ErrorType)
                })
                
                
                
            })

        

    }
    
    func showTowUser(show: Bool) {
        if show {
            self.nearbyUserType = .connnetedUser
           
        }else {
            self.nearbyUserType = .acceptHelper
        }
    }
    //用户状态处理
   override func handleStatusChange(statusInfo: StatusInfo) {
        
        switch statusInfo.status {
        case .normal:
            self.viewForInput.isHidden = false
            self.lineView.isHidden = false
            self.viewForContainer.isHidden = true
            self.btnHelp.isHidden = false
            self.stopHelpButton.isHidden = true
            self.showTowUser(show: false)
        case .beAccepted:
            //被接受帮助，则显示计时页面
            self.viewForInput.isHidden = true
            self.lineView.isHidden = true
            self.viewForContainer.isHidden = false
            self.btnHelp.isHidden = true
            self.stopHelpButton.isHidden = true
            self.btnStart.setTitle("开始计时", for: .normal)
            self.btnStart.backgroundColor = UIColor(colorLiteralRed: 65/255.0, green: 181/255.0, blue: 116/255.0, alpha: 1)
            
            self.showTowUser(show: true)

            //显示求助者和帮助者的行走路线
            if let d1 = Umbrella.currentAccepHelper.value, let d2 = Umbrella.currentAskForHelper.value {
                
                let  startCoordinate        = CLLocationCoordinate2DMake(CLLocationDegrees(d2["latitude"].floatValue), CLLocationDegrees(d2["longitude"].floatValue))
                let destinationCoordinate  = CLLocationCoordinate2DMake(CLLocationDegrees(d1["latitude"].floatValue), CLLocationDegrees(d1["longitude"].floatValue))
                
                self.searchRoute(startCoordinate: startCoordinate, destinationCoordinate: destinationCoordinate, showStartEnd: false)
                
            }

        case .waiting :
            //等待服务器请求帮助中
            self.viewForInput.isHidden = true
            self.lineView.isHidden = true
            self.viewForContainer.isHidden = true
            self.btnHelp.isHidden = true
            self.stopHelpButton.isHidden = false
            //显示路线
            let from = statusInfo.info["from"]
            let to =  statusInfo.info["to"]
            let  startCoordinate        = CLLocationCoordinate2DMake(CLLocationDegrees(from["latitude"].floatValue), CLLocationDegrees(from["longitude"].floatValue))
            let destinationCoordinate  = CLLocationCoordinate2DMake(CLLocationDegrees(to["latitude"].floatValue), CLLocationDegrees(to["longitude"].floatValue))
            self.searchRoute(startCoordinate: startCoordinate, destinationCoordinate: destinationCoordinate)
            self.showTowUser(show: false)

        case .inTrip :
            self.viewForInput.isHidden = true
            self.lineView.isHidden = true
            self.viewForContainer.isHidden = false
            self.btnHelp.isHidden = true
            self.stopHelpButton.isHidden = true
            self.btnStart.setTitle("结束计时", for: .normal)
            self.btnStart.backgroundColor = .red
            self.showTowUser(show: true)

            
            self.nearbyUserType = .allUser
            if let json =  User.statusInfo.value?.info {
                self.lblNickName.text = json["acceptHelpUser"]["name"].stringValue
                self.imageHeader.sd_setImage(with: URL(string: json["acceptHelpUser"]["avator"].stringValue), placeholderImage: UIImage(named: "空白头像"))
            }

            //显示路线
            let from = statusInfo.info["from"]
            let to =  statusInfo.info["to"]
            let  startCoordinate        = CLLocationCoordinate2DMake(CLLocationDegrees(from["latitude"].floatValue), CLLocationDegrees(from["longitude"].floatValue))
            let destinationCoordinate  = CLLocationCoordinate2DMake(CLLocationDegrees(to["latitude"].floatValue), CLLocationDegrees(to["longitude"].floatValue))
            self.searchRoute(startCoordinate: startCoordinate, destinationCoordinate: destinationCoordinate)

        default:
            break
        }
        
    }
    
    
    
    open override func beforePopNext(_ withdata:Any?){
        if isStartAddress {
            if withdata != nil {
                startAddress.value = withdata as! AddressModel
                self.btnSelectStartAddr.setTitle(startAddress.value!.address, for: .normal)
            }
        }else{
            if withdata != nil {
                endAddress.value = withdata as! AddressModel
                self.btnSelectEndAddr.setTitle(endAddress.value!.address, for: .normal)
            }
        }
    }
}



extension HelperVC {
    
    func walkManager(onCalculateRouteSuccess walkManager: AMapNaviWalkManager) {
        print("CalculateRouteSuccess")
        
        //显示路径或开启导航
        if let route = walkManager.naviRoute {
            var lineCoordinates: [CLLocationCoordinate2D] = []
            
            for  coor in route.routeCoordinates {
                lineCoordinates.append(CLLocationCoordinate2D(latitude: CLLocationDegrees(coor.latitude), longitude: CLLocationDegrees(coor.longitude)))
            }
            
            let polyline: MAPolyline = MAPolyline(coordinates: &lineCoordinates, count: UInt(lineCoordinates.count))
            mapView.add(polyline)
        }
    }
    
  
    
    
    func startSearch() {
        
        guard let s = self.startAddress.value, let e = self.endAddress.value else {
            return
        }
        
        let  startCoordinate        = CLLocationCoordinate2DMake(CLLocationDegrees(s.latitude), CLLocationDegrees(s.longitude))
        let destinationCoordinate  = CLLocationCoordinate2DMake(CLLocationDegrees(e.latitude), CLLocationDegrees(e.longitude))
        self.searchRoute(startCoordinate: startCoordinate, destinationCoordinate: destinationCoordinate)
        
        
    }
    
    
}



